const http = require('http');
const fs = require('fs');

const server = http.createServer((request, response) => {
  const {url, method, headers} = request;
  console.log(headers.accept.indexOf('image/*'))
  if (url === '/' && method === 'GET' && headers.accept.indexOf('image/*') === -1) {
    fs.readFile('index.html', (err, data) => {
      if (err) {
        response.writeHead(500, { 'Content-Type':'text/plain;charset=utf-8' });
        response.end('500，服务器错误');
        return ;
      }
      response.statusCode = 200;
      response.setHeader('Content-Type', 'text/html');
      console.log('请求成功1')
      response.end(data);
    });
  } else if(url === '/users' && method === 'GET') {
    response.writeHead(200, { 'Content-Type': 'application/json' });
    console.log('请求成功2')
    response.end(JSON.stringify([
      {
        name:'tom',
        age:20,
        address: '上海'
      }
    ]));
  } else if(method === 'GET' && headers.accept.indexOf('image/*') !== -1){
    console.log('请求成功3')
    // 图片文件服务
    fs.createReadStream('./'+url).pipe(response)
  } else {
    console.log('请求成功4')
    response.statusCode = 404;
    response.setHeader('Content-Type', 'text/plain;charset=utf-8');
    response.end('404, ⻚⾯没有找到');
  }
});
server.listen(3000);
